package com.anpai.main;

import com.anpai.entity.TitlesBean;
import com.anpai.entity.UserBean;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.poifs.filesystem.POIFSFileSystem;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.List;

import static com.anpai.main.CheckMessage.userBean;
import static com.anpai.main.LoginJFrame.*;

public class ExamJFrame extends JFrame{

    public static int allTime = 20 * 60;
    public static String result [][] = new String[20][1];
    public static int allResult = 0;
    static int i = 0;
    private static JLabel surplusTime;
    private static JLabel getSurplusTime() {
        if (surplusTime == null) {
            surplusTime = new JLabel("");
            surplusTime.setBounds(82, 88, 100, 50);
            surplusTime.setFont(new Font("微软雅黑", Font.BOLD, 12));
            java.util.Timer timer = new java.util.Timer();
            String time0 = "00:20:00";
            String strMsg = "<html><body>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;倒计时："+time0+"</body></html>";
            surplusTime.setText(strMsg);
            timer.schedule(new TimerTask() {
                public void run() {
                    if (allTime>0){
                        long hh = allTime / 60 / 60 % 60;
                        long mm = allTime / 60 % 60;
                        long ss = allTime % 60;
                        String time0 = hh+":"+mm+":"+ss;
//                        System.out.println("还剩" + hh + "小时" + mm + "分钟" + ss + "秒");
                        String strMsg = "<html><body>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;倒计时："+time0+"</body></html>";
                        surplusTime.setText(strMsg);
                    }
                    allTime--;
                    if(allTime < 0){

                    }
                }
            }, 0, 1000);
        }
        return surplusTime;
    }

    static class MyLayout extends JFrame implements ActionListener {

        JButton lastBt = new MyJButton("上一题");
        JButton nextBt = new MyJButton("下一题");
        JButton finishBt = new MyJButton("交卷");
        JButton exitBt = new MyJButton("退出");
        JRadioButton jbA = new JRadioButton("A选项");
        JRadioButton jbB = new JRadioButton("B选项");
        JRadioButton jbC = new JRadioButton("C选项");
        JRadioButton jbD = new JRadioButton("D选项");
        JTextArea jTextArea = new JTextArea(10,50);
        List<TitlesBean> values = new ArrayList<TitlesBean>();
        ButtonGroup group=new ButtonGroup();
        JLabel jLabelTime = new JLabel();

        JPanel headJPanel = new JPanel();
        JPanel centerJPanel = new JPanel(new BorderLayout());

        public MyLayout(){
            this.setTitle("考试系统-正在考试");
            setLocation(10, 10);
            setBounds(500, 330, 800, 500);
            setLayout(new BorderLayout(10,10)); // 上下左右间距10

            // 顶部部分
            lastBt.addActionListener(this);
            nextBt.addActionListener(this);
            finishBt.addActionListener(this);
            exitBt.addActionListener(this);

            headJPanel.setLayout(new GridBagLayout());
            GridBagConstraints gbc = new GridBagConstraints();
            gbc.fill = GridBagConstraints.BOTH;

            gbc.gridx = 1;
            gbc.gridy = 1;
            gbc.gridwidth = 1;
            gbc.gridheight = 1;
            gbc.weightx = 1;
            gbc.weighty = 1;
            headJPanel.add(lastBt, gbc);

            gbc.gridx = 2;
            gbc.gridy = 1;
            gbc.gridwidth = 1;
            gbc.gridheight = 1;
            gbc.weightx = 1;
            gbc.weighty = 1;
            headJPanel.add(nextBt, gbc);

            gbc.gridx = 3;
            gbc.gridy = 1;
            gbc.gridwidth = 1;
            gbc.gridheight = 1;
            gbc.weightx = 1;
            gbc.weighty = 1;
            headJPanel.add(finishBt, gbc);

            gbc.gridx = 4;
            gbc.gridy = 1;
            gbc.gridwidth = 1;
            gbc.gridheight = 1;
            gbc.weightx = 1;
            gbc.weighty = 1;
            headJPanel.add(getSurplusTime(), gbc);
            gbc.gridx = 5;
            gbc.gridy = 1;
            gbc.gridwidth = 1;
            gbc.gridheight = 1;
            gbc.weightx = 1;
            gbc.weighty = 1;
            headJPanel.add(exitBt, gbc);


            add(headJPanel, BorderLayout.NORTH);

            // 中间部分
            // 获取题库
            String key = null;
            Iterator it = titleMap.keySet().iterator();
            while (it.hasNext()) {
                key = (String) it.next();
                values.add(titleMap.get(key));
            }
            centerJPanel.setBackground(Color.BLACK);
            jTextArea.setLineWrap(true);        //激活自动换行功能
            jTextArea.setWrapStyleWord(true);            // 激活断行不断字功能
            jTextArea.setEditable(false);
            JScrollPane scroll = new JScrollPane(jTextArea);
            GridBagConstraints gbcABCD = new GridBagConstraints();
            JPanel jPanelBt = new JPanel(new GridBagLayout());
            getMessage();

            //把单选按钮添加到按钮组中，这样只能选组中的一个按钮，真正实现单选
            group.add(jbA);
            group.add(jbB);
            group.add(jbC);
            group.add(jbD);

            gbcABCD.gridx = 1;
            gbcABCD.gridy = 1;
            gbcABCD.gridwidth = 1;
            gbcABCD.gridheight = 1;
            gbcABCD.weightx = 1;
            gbcABCD.weighty = 1;
            jPanelBt.add(jbA, gbcABCD);
            gbcABCD.gridx = 1;
            gbcABCD.gridy = 2;
            gbcABCD.gridwidth = 1;
            gbcABCD.gridheight = 1;
            gbcABCD.weightx = 1;
            gbcABCD.weighty = 1;
            jPanelBt.add(jbB, gbcABCD);
            gbcABCD.gridx = 1;
            gbcABCD.gridy = 3;
            gbcABCD.gridwidth = 1;
            gbcABCD.gridheight = 1;
            gbcABCD.weightx = 1;
            gbcABCD.weighty = 1;
            jPanelBt.add(jbC, gbcABCD);
            gbcABCD.gridx = 1;
            gbcABCD.gridy = 4;
            gbcABCD.gridwidth = 1;
            gbcABCD.gridheight = 1;
            gbcABCD.weightx = 1;
            gbcABCD.weighty = 1;
            jPanelBt.add(jbD, gbcABCD);

            //把定义的JTextArea放到JScrollPane里面去
            //分别设置水平和垂直滚动条自动出现
            scroll.setHorizontalScrollBarPolicy(
                    JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
            scroll.setVerticalScrollBarPolicy(
                    JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED);
            centerJPanel.add(jTextArea,BorderLayout.NORTH);
            centerJPanel.add(jPanelBt);
            add(centerJPanel);

            currenttime ct=new currenttime();
            ct.start();
            // 底部部分
            JPanel bottomJPanel = new JPanel();
            bottomJPanel.setBackground(Color.CYAN);
            JLabel jLabelName = new JLabel("姓名："+userBean.getName());
            JLabel jLabelNumber= new JLabel("学号："+userBean.getStudentNo());
            JLabel jLabelSubject= new JLabel("科目：心理测试");
            JLabel jLabelTopics= new JLabel("题目数量：20");
            bottomJPanel.add(jLabelName);
            bottomJPanel.add(jLabelNumber);
            bottomJPanel.add(jLabelSubject);
            bottomJPanel.add(jLabelTopics);
            bottomJPanel.add(jLabelTime);

            add(bottomJPanel, BorderLayout.SOUTH);
            setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            setVisible(true);
        }
        // 动态时间创建
        class currenttime extends Thread
        {
            Date datedisplay;
            GregorianCalendar gccalendar;
            String strtime;
            public currenttime(){}
            public void run()
            {
                while(true)
                {
                    displaytime();
                    try
                    {
                        this.sleep(1000);
                    }
                    catch(InterruptedException e)
                    {
                        JOptionPane.showMessageDialog(null,"线程中断");
                    }
                }
            }
            public void displaytime()
            {
                datedisplay=new Date();
                gccalendar=new GregorianCalendar();
                gccalendar.setTime(datedisplay);
                strtime= "当前时间："+dateChange(gccalendar.getTime(),"yyyy年MM月dd日 hh:mm:ss");
                jLabelTime.setText(strtime);
            }

            public String dateChange(Date date, String pattern) {
                SimpleDateFormat sdf = new SimpleDateFormat(pattern);
                String demo = sdf.format(date);
                return demo;
            }
        }
        public void getMessage(){
            if(i==0){
                lastBt.setEnabled(false);
            }
            else if(i==19){
                nextBt.setEnabled(false);
            }
            else{
                nextBt.setEnabled(true);
                lastBt.setEnabled(true);
            }
            String txtMessage = i+1 + "、" + values.get(i).getTitle();
            String titleKey = values.get(i).getTitleKey();
            System.out.println("第"+i+1+"题, 首选是 "+titleKey);
            String secondKye = values.get(i).getSecondKye();
            System.out.println("第"+i+1+"题, 次选是 "+secondKye);
            jTextArea.setText(txtMessage);
            jbA.setText(values.get(i).getCheckA());
            jbB.setText(values.get(i).getCheckB());
            jbC.setText(values.get(i).getCheckC());
            jbD.setText(values.get(i).getCheckD());
            group.clearSelection();
            if(result[i][0]=="A"){
                jbA.setSelected(true);
            }
            if(result[i][0]=="B"){
                jbB.setSelected(true);
            }
            if(result[i][0]=="C"){
                jbC.setSelected(true);
            }
            if(result[i][0]=="D"){
                jbD.setSelected(true);
            }
        }

        @Override
        public void actionPerformed(ActionEvent e) {
            if(jbA.isSelected()){
                result[i][0]="A";
            }
            else if(jbB.isSelected()){
                result[i][0]="B";
            }
            else if(jbC.isSelected()){
                result[i][0]="C";
            }
            else if(jbD.isSelected()){
                result[i][0]="D";
            }
            if(e.getSource() == lastBt){
                --i;
                getMessage();
            }
            if(e.getSource() == nextBt){
                ++i;
                getMessage();
            }
            if(e.getSource() == finishBt){
                int confirm = JOptionPane.showConfirmDialog(null, "你确定交卷了吗？", "交卷", JOptionPane.YES_NO_OPTION);
                if(confirm == 0) {
                    for(int i = 0;i<result.length;i++){
                        for(int j=0;j<result[i].length;j++){
                            if(values.get(i).getTitleKey().equals(result[i][j])){
                                allResult = allResult + 4;
                            }else if(values.get(i).getSecondKye().equals(result[i][j])){
                                allResult = allResult + 3;
                            }else if(values.get(i).getThirdKey().equals(result[i][j])){
                                allResult = allResult + 2;
                            }else
                                allResult = allResult+0;
                        }
                    }

                    this.setVisible(false);
                    JFrame jFrame = new JFrame("考试系统-成绩单");
                    jFrame.setBounds(550,300,500,300);
                    jFrame.setLayout(new BorderLayout());
                    JLabel jLabel = null;
                    registerFrame rf = new registerFrame();
                    try {
                        rf.write(userBean, String.valueOf(allResult), Integer.valueOf(userBean.getUserId()));
                    } catch (Exception exception) {
                        exception.printStackTrace();
                    }
                    int n=allResult/10;
                    switch (n){
                        case 9:
                        case 8:
                        case 7:jLabel=new JLabel("<html><body style='text-align:center;'><h1>"+"尊敬的"+userBean.getName()+"、学号为"+userBean.getStudentNo()+"的考生：<br>您此次的成绩是："+allResult+"分" +
                                "<br>心理健康等级 良好"+   "</h1></body></html>");break;

                        case 6:jLabel=new JLabel("<html><body style='text-align:center;'><h1>"+"尊敬的"+userBean.getName()+"、学号为"+userBean.getStudentNo()+"的考生：<br>您此次的成绩是："+allResult+"分" +
                                "<br>心理健康等级 一般"+   "</h1></body></html>");break;

                                default:jLabel=new JLabel("<html><body style='text-align:center;'><h1>"+"尊敬的"+userBean.getName()+"、学号为"+userBean.getStudentNo()+"的考生：<br>您此次的成绩是："+allResult+"分" +
                                "<br>心理健康等级 不合格  "+   "</h1></body></html>");break;

                    }
                    JButton jButtonExit = new JButton("退出");
                    JButton jButtonBack = new JButton("首页");
                    jFrame.add(jLabel,BorderLayout.CENTER);
                    jFrame.add(jButtonBack,BorderLayout.NORTH);
                    jFrame.add(jButtonExit,BorderLayout.SOUTH);

                    ActionListener actionListener = new AbstractAction() {
                        @Override
                        public void actionPerformed(ActionEvent e) {
                            if(e.getSource() == jButtonBack){
                                for(int ind = 0; ind < 20; ind++){
                                    result[ind][0] = null;
                                }
                                group.clearSelection();
                                allResult = 0;
                                jFrame.setVisible(false);
                                new LoginJFrame();
                            }
                            else if(e.getSource() == jButtonExit){
                                System.exit(0);
                            }
                        }
                    };
                    jButtonBack.addActionListener(actionListener);
                    jButtonExit.addActionListener(actionListener);
                    jFrame.setVisible(true);
                    jFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                }

                System.out.println(allResult);
            }
            if(e.getSource() == exitBt){
                int confirm = JOptionPane.showConfirmDialog(null, "你确定要退出吗？", "退出", JOptionPane.YES_NO_OPTION);
                if(confirm == 0) {
                    System.exit(0);
                }
            }
        }
    }

}
